<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listUsers, updateUser, exportUserExcel } from '@/api/user'
import { Refresh, Edit, Search, Plus, Download } from '@element-plus/icons-vue'

const loading = ref(false)
const filters = ref({
  username: '',
  role: null,
  page: 1,
  size: 8
})

const tableData = ref({
  records: [],
  total: 0
})

const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const form = reactive({
  id: null,
  username: '',
  role: null,
  mail: '',
  phone: ''
})

const rules = {
  username: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  mail: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

const formRef = ref()
const selectedRows = ref([])

const searchTimeout = ref(null)

const handleSearch = () => {
  if (searchTimeout.value) {
    clearTimeout(searchTimeout.value)
  }
  searchTimeout.value = setTimeout(() => {
    filters.value.page = 1
    fetchData()
  }, 300)
}

const fetchData = async () => {
  loading.value = true
  try {
    const res = await listUsers(filters.value)
    if (res.code === 0) {
      tableData.value = {
        records: res.data.records,
        total: res.data.total
      }
      filters.value.page = res.data.current
      filters.value.size = res.data.size
    }
  } catch (e) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const handlePageChange = (val) => {
  filters.value.page = val
  fetchData()
}

const resetFilters = () => {
  ElMessageBox.confirm('确定要重置所有筛选条件吗？', '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(() => {
    filters.value = { username: '', role: null, page: 1, size: 8 }
    fetchData()
  }).catch(() => {})
}

const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑用户'
  isEdit.value = true
  Object.assign(form, row)
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    await updateUser(form)
    ElMessage.success('修改成功')
    dialogVisible.value = false
    fetchData()
  } catch (e) {
    if (e instanceof Error) {
      ElMessage.error('修改失败')
    }
  }
}

const handleExport = async () => {
  try {
    const res = await exportUserExcel()
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '用户列表.xlsx'
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (e) {
    ElMessage.error('导出失败')
  }
}

onMounted(() => {
  fetchData()
})
</script>

<template>
  <div class="users-page">
    <el-form :inline="true" :model="filters" class="filter-form" @submit.prevent>
      <el-form-item label="姓名">
        <el-input 
          v-model="filters.username" 
          placeholder="输入姓名" 
          clearable 
          @input="handleSearch"
          @clear="handleSearch"
        />
      </el-form-item>
      <el-form-item label="角色" style="min-width: 180px;">
        <el-select 
          v-model="filters.role" 
          placeholder="全部" 
          clearable 
          style="width: 140px;"
          @change="handleSearch"
        >
          <el-option label="管理员" :value="0" />
          <el-option label="学生" :value="1" />
          <el-option label="教师" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchData" :icon="Search">查询</el-button>
        <el-button @click="resetFilters" :icon="Refresh">重置</el-button>
      </el-form-item>
      <el-form-item style="float:right;margin-left:auto;">
        <el-button type="success" @click="handleExport" :icon="Download">导出</el-button>
      </el-form-item>
    </el-form>
    
    <div class="users-table-wrapper">
      <el-table 
        :data="tableData.records" 
        style="width: 100%;" 
        height="100%"
        v-loading="loading"
        element-loading-text="加载中..."
        :empty-text="loading ? '' : '暂无数据'"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" fixed="left" />
        <el-table-column prop="id" label="学号/工号" width="120" />
        <el-table-column prop="username" label="姓名" width="120" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="row.role === 0 ? 'danger' : row.role === 1 ? 'success' : 'info'" effect="plain">
              {{ row.role === 0 ? '管理员' : row.role === 1 ? '学生' : '教师' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="mail" label="邮箱" show-overflow-tooltip min-width="200" />
        <el-table-column prop="phone" label="联系方式" show-overflow-tooltip width="150" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="handleEdit(row)" :icon="Edit">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <div class="pagination-wrapper">
      <el-pagination
        background
        layout="prev, pager, next, jumper, ->, total"
        :total="tableData.total"
        :page-size="filters.size"
        :current-page="filters.page"
        @current-change="handlePageChange"
      />
    </div>
    
    <!-- 用户编辑弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="500px"
      :close-on-click-modal="false"
      @closed="formRef?.resetFields()"
    >
      <el-form 
        :model="form" 
        :rules="rules"
        ref="formRef" 
        label-width="100px"
        @submit.prevent
      >
        <el-form-item label="姓名" prop="username">
          <el-input v-model="form.username" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="管理员" :value="0" />
            <el-option label="学生" :value="1" />
            <el-option label="教师" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="mail">
          <el-input v-model="form.mail" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系方式" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.users-page {
  padding: 20px;
  min-height: calc(100vh - 60px);
  background-color: #f5f7fa;
}

.filter-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.users-table-wrapper {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
  min-height: 500px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

:deep(.el-table) {
  border-radius: 8px;
  --el-table-border-color: var(--el-border-color-lighter);
}

:deep(.el-table th) {
  background-color: var(--el-fill-color-light);
}

:deep(.el-button) {
  border-radius: 4px;
}

:deep(.el-tag) {
  border-radius: 4px;
}

:deep(.el-input) {
  border-radius: 4px;
}

:deep(.el-select) {
  border-radius: 4px;
}

:deep(.el-pagination) {
  justify-content: center;
  width: 100%;
}

:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-button--primary) {
  --el-button-hover-bg-color: var(--el-color-primary-light-3);
  --el-button-hover-border-color: var(--el-color-primary-light-3);
}

:deep(.el-button--success) {
  --el-button-hover-bg-color: var(--el-color-success-light-3);
  --el-button-hover-border-color: var(--el-color-success-light-3);
}

:deep(.el-button--danger) {
  --el-button-hover-bg-color: var(--el-color-danger-light-3);
  --el-button-hover-border-color: var(--el-color-danger-light-3);
}
</style> 